import { createApp } from "vue";
import "./style.css";
import App2 from "./App.vue";
import router from "./router/router.ts";
import {
  renderWithQiankun,
  qiankunWindow,
} from "vite-plugin-qiankun/dist/helper";

let instance: any = null;
let instanceCache: any = null;
function render(props: any = {}) {
  const { container,cache } = props;
  instanceCache = cache;
  let vnode = cache.get('vue3Ts');
    const Root = {
    render() {
      return vnode;
    }
  };
  instance = createApp(vnode ? Root : App2);
  instance.use(router);
  // instance.use(store);
  const mountPoint = container
    ? container.querySelector("#vue3Ts")
    : document.querySelector("#vue3Ts");
  if (mountPoint) {
    instance.mount(mountPoint);
  }
}

if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render();
}

renderWithQiankun({
  mount(props: any) {
    render(props);
    if (instance) {
      instance.config.globalProperties.$onGlobalStateChange =
        props.onGlobalStateChange;
      instance.config.globalProperties.$setGlobalState = props.setGlobalState;
    }
  },
  bootstrap() {
    console.log("%c%s", "color: green;", "vue3.0 app bootstraped");
  },
  unmount() {
    if (instance) {
      console.log(instance);
      instanceCache.set('vue3Ts',instance._container._vnode);
      instance.unmount();
      // 清空子应用内容
      const container = document.querySelector("#vue3Ts");
      if (container) {
        container.innerHTML = "";
      }
      instance = null;
    }
  },
});
